<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box1{width:1000px;height:100px;padding:10px 0;position: relative;border: solid 1px black;margin-bottom:50px;}
        .xbox1{width:100px;height:100px;background: red;position: absolute;left:0;}
        .box2{width:1000px;height:100px;padding:10px 0;position: relative;border: solid 1px black;}
        .xbox2{width:100px;height:100px;background: red;position: absolute;left:0;}
    </style>
</head>
<body>
    <div class="box1">
        <div class="xbox1"></div>
    </div>

    <div class="box2">
        <div class="xbox2"></div>
    </div>
</body>
<script>

    const obox1 = document.querySelector(".box1");
    const obox2 = document.querySelector(".box2");
    const oxbox1 = document.querySelector(".xbox1");
    const oxbox2 = document.querySelector(".xbox2");

    obox1.onmouseover = function(){
        move(oxbox1, "left", 900);
    }

    obox2.onmouseover = function(){
        move(oxbox2, "left", 900);
    }

    function move(ele, attr, target){
        // 将计时器绑定到元素对象身上，既能保证一个元素只有一个计时器，又能保证多个元素之间有多个计时器
        clearInterval(ele.time);
        ele.time = setInterval(()=>{
            let now = parseInt(getStyle(ele, attr));

            let speed = (target - now) / 10;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

            if(target === now){
                clearInterval(ele.time);
            }else{
                ele.style[attr] = now + speed + "px";
            }
        }, 30);
    }

    // 获取非行内样式的兼容封装
    function getStyle(ele, attr){
        if(getComputedStyle){
            return getComputedStyle(ele)[attr];
        }else{
            return ele.currentStyle[attr];
        }
    }

    
</script>
</html>